#!/bin/bash

# Log Server Linux Service Uninstallation Script

set -e

echo "Uninstalling Log Server Linux systemd service..."
echo

# Check if running as root
if [ "$EUID" -ne 0 ]; then
    echo "Error: This script must be run as root (use sudo)"
    exit 1
fi

# Stop the service if running
echo "Stopping log-server service..."
if systemctl is-active --quiet log-server; then
    systemctl stop log-server
    echo "Service stopped"
else
    echo "Service is not running"
fi

# Disable the service
echo "Disabling log-server service..."
if systemctl is-enabled --quiet log-server; then
    systemctl disable log-server
    echo "Service disabled"
else
    echo "Service is not enabled"
fi

# Remove systemd service file
echo "Removing systemd service file..."
if [ -f "/etc/systemd/system/log-server.service" ]; then
    rm /etc/systemd/system/log-server.service
    echo "Service file removed"
else
    echo "Service file not found"
fi

# Reload systemd
echo "Reloading systemd..."
systemctl daemon-reload
systemctl reset-failed

# Ask user if they want to remove service directory
echo
read -p "Do you want to remove the service directory /opt/log-server? (y/N): " -n 1 -r
echo
if [[ $REPLY =~ ^[Yy]$ ]]; then
    if [ -d "/opt/log-server" ]; then
        rm -rf /opt/log-server
        echo "Service directory removed"
    else
        echo "Service directory not found"
    fi
else
    echo "Service directory preserved"
fi

# Ask user if they want to remove service user
echo
read -p "Do you want to remove the service user 'logserver'? (y/N): " -n 1 -r
echo
if [[ $REPLY =~ ^[Yy]$ ]]; then
    if id "logserver" &>/dev/null; then
        userdel logserver
        echo "Service user removed"
    else
        echo "Service user not found"
    fi
else
    echo "Service user preserved"
fi

echo
echo "Uninstallation completed successfully!"
echo "The log-server service has been removed from systemd."